/* model */
import Field from '@model/entity/Field'
import { ConnectorBizTypeEnum, ConnectorModuleComponentNameEnum } from '@src/modules/connector/model'
/* mixin */
import { ConnectorModuleConnectorCreateMixin } from '@src/modules/connector/mixin'
/* vue */
import Component from 'vue-class-component'
/* util */
import Log from '@src/util/log'
import { initialize } from '@src/component/form/util'
import { packToForm } from '@src/modules/event/util/event'
import { getConnectorCreateDataSessionKeyByBizType } from '@src/modules/connector/util'

@Component({ 
  name: ConnectorModuleComponentNameEnum.ConnectorModuleConnectorCreateEventMixin,
})
export default class ConnectorModuleConnectorCreateEventMixin extends ConnectorModuleConnectorCreateMixin {
  
  /* 连接器新建数据 session 键 */
  public connectorCreateDataSessionKey = getConnectorCreateDataSessionKeyByBizType(ConnectorBizTypeEnum.Event)
  
  /* 连接下新建配置数据 */
  public connectorMessageData: Record<string, any> = {}
  
  /* 混入的组件需要重写此属性 */
  private basicValue: Record<string, any> = {}
  /* 混入的组件需要重写此属性 */
  private basicFields: Field[] = []
  
  /* 混入的组件需要重写此属性 */
  get fieldNameMap(): Record<string, any> {
    return (
      this.basicFields.reduce((previousValue, currentValue) => {
        previousValue[currentValue.fieldName] = currentValue
        return previousValue
      }, {} as Record<string, any>)
    )
  }
  
  /**
   * @description 消息处理后的事件
  */
  public onFrameMessageAfterHandler() {
    // setTimeout(() => {
    //   this.fetchConnectorInsertSelectCall()
    // }, 800)
  }
  
  /** 
   * @description 连接器新建数据处理
  */
  public connectorInsertSelectCallDataHandler(data: Record<string, any>) {
    
    Log.info(data, 'data', this.connectorInsertSelectCallDataHandler.name)
    
    // 初始化解析表单数据
    let form = packToForm(this.basicFields, data)
    
    Log.info(form, 'form', this.connectorInsertSelectCallDataHandler.name)
    
    const newValue = initialize(this.basicFields, form)
    
    Object.keys(newValue).forEach(key => {
      const value = newValue[key]
      this.$set(this.basicValue, key, value)
    })
    
    Log.info(this.basicValue, 'this.basicValue', this.connectorInsertSelectCallDataHandler.name)
    
    // 连接器新建的事件不允许修改事件类型
    const eventNoField = this.fieldNameMap.eventNo || {}
    eventNoField.disabled = true
    
    this.$nextTick(() => {
      // 重新渲染表单
      try {
        
        // this.$refs.formEditRef.$refs.form.rerender()
        this.$refs.formEditRef.outsideUpdateCustomer()
        
      } catch (error) {
        
        Log.error(error, this.connectorInsertSelectCallDataHandler.name)
        Log.error('重新渲染事件表单失败，请检查', this.connectorInsertSelectCallDataHandler.name)
        
      }
    })
    
  }
  
}

